# import pygame
# import random
# import os
#
# # 初始化Pygame
# pygame.init()
#
# # 游戏窗口设置
# SCREEN_WIDTH = 480
# SCREEN_HEIGHT = 720
# screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
# pygame.display.set_caption("羊了个羊")
#
# # 颜色定义
# BG_COLOR = (255, 255, 255)
#
# # 卡片尺寸和间距
# CARD_WIDTH = 55
# CARD_HEIGHT = 70
# SPACING = 10
#
# # 游戏区域布局
# GRID_ROWS = 4
# GRID_COLS = 4
# grid_width = GRID_COLS * (CARD_WIDTH + SPACING) - SPACING
# GRID_LEFT = (SCREEN_WIDTH - grid_width) // 2
# GRID_TOP = 100
#
# # 槽位区域设置
# SLOT_ROWS = 1
# SLOT_COLS = 7  # 最多存放7个卡片
# slot_width = SLOT_COLS * (CARD_WIDTH + 5) - 5
# SLOT_LEFT = (SCREEN_WIDTH - slot_width) // 2
# SLOT_TOP = SCREEN_HEIGHT - CARD_HEIGHT - 50
# SLOT_HEIGHT = CARD_HEIGHT + 20
#
# # 加载背景图像
# try:
#     image_folder = os.path.join(os.path.dirname(__file__), "image")
#     background_path = os.path.join(image_folder, "back.png")
#     background_img = pygame.image.load(background_path)
#     background_img = pygame.transform.scale(background_img, (SCREEN_WIDTH, SCREEN_HEIGHT))
#     print("主背景图像加载成功")
# except Exception as e:
#     print(f"主背景图像加载失败: {e}")
#     background_img = None
#
# # 加载槽位背景图像
# try:
#     slot_bg_path = os.path.join(image_folder, "back2.png")
#     slot_bg_img = pygame.image.load(slot_bg_path)
#     slot_bg_img = pygame.transform.scale(slot_bg_img, (slot_width + 20, SLOT_HEIGHT + 20))
#     print("槽位背景图像加载成功")
# except Exception as e:
#     print(f"槽位背景图像加载失败: {e}")
#     slot_bg_img = None
#
# # 加载卡片图片
# card_images = []
# try:
#     for i in range(5):
#         if i == 0:
#             tile_path = os.path.join(image_folder, "tile.png")
#         else:
#             tile_path = os.path.join(image_folder, f"tile{i}.png")
#
#         if os.path.exists(tile_path):
#             img = pygame.image.load(tile_path)
#             img = pygame.transform.scale(img, (CARD_WIDTH, CARD_HEIGHT))
#             card_images.append(img)
#             print(f"卡片图片 {os.path.basename(tile_path)} 加载成功")
#         else:
#             print(f"卡片图片 {tile_path} 不存在")
#
#     if not card_images:
#         raise Exception("没有找到任何卡片图片")
#
# except Exception as e:
#     print(f"卡片图片加载失败: {e}")
#     COLORS = [
#         (255, 0, 0),  # 红
#         (0, 255, 0),  # 绿
#         (0, 0, 255),  # 蓝
#         (255, 255, 0),  # 黄
#         (128, 0, 128),  # 紫
#     ]
#
# # 游戏状态
# slots = []
# score = 0
# game_over = False
# game_won = False
#
#
# def check_victory():
#     """检查是否胜利"""
#     for row in grid:
#         for stack in row:
#             if len(stack) > 0:
#                 return False
#     return len(slots) == 0
#
#
# # 初始化卡片堆
# grid = []
# for row in range(GRID_ROWS):
#     grid_row = []
#     for col in range(GRID_COLS):
#         layers = random.randint(3, 5)
#         max_card_type = len(card_images) - 1 if card_images else len(COLORS) - 1
#         stack = [random.randint(0, max_card_type) for _ in range(layers)]
#         stack += [stack[-1]] * (3 - layers % 3) if layers % 3 != 0 else []
#         grid_row.append(stack)
#     grid.append(grid_row)
#
# # 主循环
# clock = pygame.time.Clock()
# running = True
#
# while running:
#     # 事件处理
#     for event in pygame.event.get():
#         if event.type == pygame.QUIT:
#             running = False
#         elif event.type == pygame.MOUSEBUTTONDOWN and not game_over:
#             x, y = pygame.mouse.get_pos()
#             # 计算点击位置
#             grid_col = (x - GRID_LEFT) // (CARD_WIDTH + SPACING)
#             grid_row = (y - GRID_TOP) // (CARD_HEIGHT + SPACING)
#             # 检查点击范围
#             if 0 <= grid_row < GRID_ROWS and 0 <= grid_col < GRID_COLS:
#                 if len(grid[grid_row][grid_col]) > 0:
#                     # 检查槽位是否已满（改为7块）
#                     if len(slots) >= SLOT_COLS:  # SLOT_COLS = 7
#                         game_over = True
#                         continue
#
#                     # 取出顶层卡片
#                     card = grid[grid_row][grid_col].pop()
#                     slots.append(card)
#
#                     # 检查连续三个相同卡片
#                     if len(slots) >= 3 and slots[-1] == slots[-2] == slots[-3]:
#                         del slots[-3:]
#                         score += 1
#
#                     # 再次检查槽位是否已满
#                     if len(slots) >= SLOT_COLS:
#                         game_over = True
#
#                     # 检查胜利条件
#                     if check_victory():
#                         game_won = True
#                         game_over = True
#
#     # 绘制界面
#     if background_img:
#         screen.blit(background_img, (0, 0))
#     else:
#         screen.fill(BG_COLOR)
#
#     # 绘制卡片堆
#     for row in range(GRID_ROWS):
#         for col in range(GRID_COLS):
#             x = GRID_LEFT + col * (CARD_WIDTH + SPACING)
#             y = GRID_TOP + row * (CARD_HEIGHT + SPACING)
#             if len(grid[row][col]) > 0:
#                 card_type = grid[row][col][-1]
#                 if card_images:
#                     screen.blit(card_images[card_type], (x, y))
#                 else:
#                     pygame.draw.rect(screen, COLORS[card_type], (x, y, CARD_WIDTH, CARD_HEIGHT))
#
#     # 绘制槽位背景
#     if slot_bg_img:
#         screen.blit(slot_bg_img, (SLOT_LEFT - 10, SLOT_TOP - 10))
#     else:
#         pygame.draw.rect(screen, (200, 200, 200),
#                          (SLOT_LEFT - 5, SLOT_TOP - 5,
#                           slot_width + 10, SLOT_HEIGHT + 10),
#                          border_radius=10)
#
#     # 绘制槽位中的卡片
#     for i, card in enumerate(slots):
#         x = SLOT_LEFT + i * (CARD_WIDTH + 5)
#         if card_images:
#             screen.blit(card_images[card], (x, SLOT_TOP))
#         else:
#             pygame.draw.rect(screen, COLORS[card], (x, SLOT_TOP, CARD_WIDTH, CARD_HEIGHT))
#
#     # 绘制状态信息
#     font = pygame.font.Font(None, 36)
#     text = font.render(f"Score: {score}", True, (0, 0, 0))
#     screen.blit(text, (20, 20))
#
#     # 绘制槽位容量提示
#     capacity_text = font.render(f"{len(slots)}/{SLOT_COLS}", True, (100, 100, 100))
#     screen.blit(capacity_text, (SCREEN_WIDTH - 60, 20))
#
#     if game_over:
#         text = font.render("YOU WIN!" if game_won else "GAME OVER!",
#                            True, (0, 255, 0) if game_won else (255, 0, 0))
#         screen.blit(text, (SCREEN_WIDTH // 2 - 80, SCREEN_HEIGHT // 2 - 20))
#
#     pygame.display.flip()
#     clock.tick(30)
#
# pygame.quit()


# import pygame
# import random
# import os
#
# # 初始化Pygame
# pygame.init()
#
# # 游戏窗口设置
# SCREEN_WIDTH = 480
# SCREEN_HEIGHT = 720
# screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
# pygame.display.set_caption("羊了个羊")
#
# # 颜色定义
# BG_COLOR = (255, 255, 255)
#
# # 卡片尺寸和间距
# CARD_WIDTH = 55
# CARD_HEIGHT = 70
# SPACING = 10
#
# # 游戏区域布局
# GRID_ROWS = 4
# GRID_COLS = 4
# grid_width = GRID_COLS * (CARD_WIDTH + SPACING) - SPACING
# GRID_LEFT = (SCREEN_WIDTH - grid_width) // 2
# GRID_TOP = 100
#
# # 槽位区域设置
# SLOT_ROWS = 1
# SLOT_COLS = 7  # 最多存放7个卡片
# slot_width = SLOT_COLS * (CARD_WIDTH + 5) - 5
# SLOT_LEFT = (SCREEN_WIDTH - slot_width) // 2
# SLOT_TOP = SCREEN_HEIGHT - CARD_HEIGHT - 50
# SLOT_HEIGHT = CARD_HEIGHT + 20
#
# # 加载背景图像
# try:
#     image_folder = os.path.join(os.path.dirname(__file__), "image")
#     background_path = os.path.join(image_folder, "back.png")
#     background_img = pygame.image.load(background_path)
#     background_img = pygame.transform.scale(background_img, (SCREEN_WIDTH * 2, SCREEN_HEIGHT))  # 背景图宽度翻倍，用于移动
#     print("主背景图像加载成功")
#     bg_x = 0  # 背景图初始x坐标
#     BG_MOVE_SPEED = 1  # 背景图移动速度
# except Exception as e:
#     print(f"主背景图像加载失败: {e}")
#     background_img = None
#     bg_x = 0
#
# # 加载槽位背景图像
# try:
#     slot_bg_path = os.path.join(image_folder, "back2.png")
#     slot_bg_img = pygame.image.load(slot_bg_path)
#     slot_bg_img = pygame.transform.scale(slot_bg_img, (slot_width + 20, SLOT_HEIGHT + 20))
#     print("槽位背景图像加载成功")
# except Exception as e:
#     print(f"槽位背景图像加载失败: {e}")
#     slot_bg_img = None
#
# # 加载卡片图片
# card_images = []
# try:
#     for i in range(5):
#         if i == 0:
#             tile_path = os.path.join(image_folder, "tile.png")
#         else:
#             tile_path = os.path.join(image_folder, f"tile{i}.png")
#
#         if os.path.exists(tile_path):
#             img = pygame.image.load(tile_path)
#             img = pygame.transform.scale(img, (CARD_WIDTH, CARD_HEIGHT))
#             card_images.append(img)
#             print(f"卡片图片 {os.path.basename(tile_path)} 加载成功")
#         else:
#             print(f"卡片图片 {tile_path} 不存在")
#
#     if not card_images:
#         raise Exception("没有找到任何卡片图片")
#
# except Exception as e:
#     print(f"卡片图片加载失败: {e}")
#     COLORS = [
#         (255, 0, 0),  # 红
#         (0, 255, 0),  # 绿
#         (0, 0, 255),  # 蓝
#         (255, 255, 0),  # 黄
#         (128, 0, 128),  # 紫
#     ]
#
# # 游戏状态
# slots = []
# score = 0
# game_over = False
# game_won = False
#
#
# def check_victory():
#     """检查是否胜利"""
#     for row in grid:
#         for stack in row:
#             if len(stack) > 0:
#                 return False
#     return len(slots) == 0
#
#
# # 初始化卡片堆
# grid = []
# for row in range(GRID_ROWS):
#     grid_row = []
#     for col in range(GRID_COLS):
#         layers = random.randint(3, 5)
#         max_card_type = len(card_images) - 1 if card_images else len(COLORS) - 1
#         stack = [random.randint(0, max_card_type) for _ in range(layers)]
#         stack += [stack[-1]] * (3 - layers % 3) if layers % 3 != 0 else []
#         grid_row.append(stack)
#     grid.append(grid_row)
#
# # 主循环
# clock = pygame.time.Clock()
# running = True
#
# while running:
#     # 事件处理
#     for event in pygame.event.get():
#         if event.type == pygame.QUIT:
#             running = False
#         elif event.type == pygame.MOUSEBUTTONDOWN and not game_over:
#             x, y = pygame.mouse.get_pos()
#             # 计算点击位置
#             grid_col = (x - GRID_LEFT) // (CARD_WIDTH + SPACING)
#             grid_row = (y - GRID_TOP) // (CARD_HEIGHT + SPACING)
#             # 检查点击范围
#             if 0 <= grid_row < GRID_ROWS and 0 <= grid_col < GRID_COLS:
#                 if len(grid[grid_row][grid_col]) > 0:
#                     # 检查槽位是否已满（改为7块）
#                     if len(slots) >= SLOT_COLS:  # SLOT_COLS = 7
#                         game_over = True
#                         continue
#
#                     # 取出顶层卡片
#                     card = grid[grid_row][grid_col].pop()
#                     slots.append(card)
#
#                     # 检查连续三个相同卡片
#                     if len(slots) >= 3 and slots[-1] == slots[-2] == slots[-3]:
#                         del slots[-3:]
#                         score += 1
#
#                     # 再次检查槽位是否已满
#                     if len(slots) >= SLOT_COLS:
#                         game_over = True
#
#                     # 检查胜利条件
#                     if check_victory():
#                         game_won = True
#                         game_over = True
#
#     # 移动背景图
#     bg_x -= BG_MOVE_SPEED
#     if bg_x <= -SCREEN_WIDTH:
#         bg_x = 0
#
#     # 绘制界面
#     if background_img:
#         screen.blit(background_img, (bg_x, 0))
#         screen.blit(background_img, (bg_x + SCREEN_WIDTH, 0))  # 绘制第二张背景图，实现无缝衔接
#     else:
#         screen.fill(BG_COLOR)
#
#     # 绘制卡片堆
#     for row in range(GRID_ROWS):
#         for col in range(GRID_COLS):
#             x = GRID_LEFT + col * (CARD_WIDTH + SPACING)
#             y = GRID_TOP + row * (CARD_HEIGHT + SPACING)
#             if len(grid[row][col]) > 0:
#                 card_type = grid[row][col][-1]
#                 if card_images:
#                     screen.blit(card_images[card_type], (x, y))
#                 else:
#                     pygame.draw.rect(screen, COLORS[card_type], (x, y, CARD_WIDTH, CARD_HEIGHT))
#
#     # 绘制槽位背景
#     if slot_bg_img:
#         screen.blit(slot_bg_img, (SLOT_LEFT - 10, SLOT_TOP - 10))
#     else:
#         pygame.draw.rect(screen, (200, 200, 200),
#                          (SLOT_LEFT - 5, SLOT_TOP - 5,
#                           slot_width + 10, SLOT_HEIGHT + 10),
#                          border_radius=10)
#
#     # 绘制槽位中的卡片
#     for i, card in enumerate(slots):
#         x = SLOT_LEFT + i * (CARD_WIDTH + 5)
#         if card_images:
#             screen.blit(card_images[card], (x, SLOT_TOP))
#         else:
#             pygame.draw.rect(screen, COLORS[card], (x, SLOT_TOP, CARD_WIDTH, CARD_HEIGHT))
#
#     # 绘制状态信息
#     font = pygame.font.Font(None, 36)
#     text = font.render(f"Score: {score}", True, (0, 0, 0))
#     screen.blit(text, (20, 20))
#
#     # 绘制槽位容量提示
#     capacity_text = font.render(f"{len(slots)}/{SLOT_COLS}", True, (100, 100, 100))
#     screen.blit(capacity_text, (SCREEN_WIDTH - 60, 20))
#
#     if game_over:
#         text = font.render("YOU WIN!" if game_won else "GAME OVER!",
#                            True, (0, 255, 0) if game_won else (255, 0, 0))
#         screen.blit(text, (SCREEN_WIDTH // 2 - 80, SCREEN_HEIGHT // 2 - 20))
#
#     pygame.display.flip()
#     clock.tick(30)
#
# pygame.quit()







# import pygame
# import random
# import os
#
# # 初始化Pygame
# pygame.init()
#
# # 游戏窗口设置
# SCREEN_WIDTH = 480
# SCREEN_HEIGHT = 720
# screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
# pygame.display.set_caption("羊了个羊")
#
# # 颜色定义
# BG_COLOR = (255, 255, 255)
#
# # 卡片尺寸和间距
# CARD_WIDTH = 55
# CARD_HEIGHT = 70
# SPACING = 10
# # 叠罗汉偏移量
# OVERLAP_OFFSET = 10
#
# # 游戏区域布局
# GRID_ROWS = 4
# GRID_COLS = 4
# grid_width = GRID_COLS * (CARD_WIDTH + SPACING) - SPACING
# GRID_LEFT = (SCREEN_WIDTH - grid_width) // 2
# GRID_TOP = 100
#
# # 槽位区域设置
# SLOT_ROWS = 1
# SLOT_COLS = 7  # 最多存放7个卡片
# slot_width = SLOT_COLS * (CARD_WIDTH + 5) - 5
# SLOT_LEFT = (SCREEN_WIDTH - slot_width) // 2
# SLOT_TOP = SCREEN_HEIGHT - CARD_HEIGHT - 50
# SLOT_HEIGHT = CARD_HEIGHT + 20
#
# # 加载背景图像
# try:
#     image_folder = os.path.join(os.path.dirname(__file__), "image")
#     background_path = os.path.join(image_folder, "back.png")
#     background_img = pygame.image.load(background_path)
#     background_img = pygame.transform.scale(background_img, (SCREEN_WIDTH * 2, SCREEN_HEIGHT))  # 背景图宽度翻倍，用于移动
#     print("主背景图像加载成功")
#     bg_x = 0  # 背景图初始x坐标
#     BG_MOVE_SPEED = 1  # 背景图移动速度
# except Exception as e:
#     print(f"主背景图像加载失败: {e}")
#     background_img = None
#     bg_x = 0
#
# # 加载槽位背景图像
# try:
#     slot_bg_path = os.path.join(image_folder, "back2.png")
#     slot_bg_img = pygame.image.load(slot_bg_path)
#     slot_bg_img = pygame.transform.scale(slot_bg_img, (slot_width + 20, SLOT_HEIGHT + 20))
#     print("槽位背景图像加载成功")
# except Exception as e:
#     print(f"槽位背景图像加载失败: {e}")
#     slot_bg_img = None
#
# # 加载卡片图片
# card_images = []
# try:
#     for i in range(5):
#         if i == 0:
#             tile_path = os.path.join(image_folder, "tile.png")
#         else:
#             tile_path = os.path.join(image_folder, f"tile{i}.png")
#
#         if os.path.exists(tile_path):
#             img = pygame.image.load(tile_path)
#             img = pygame.transform.scale(img, (CARD_WIDTH, CARD_HEIGHT))
#             card_images.append(img)
#             print(f"卡片图片 {os.path.basename(tile_path)} 加载成功")
#         else:
#             print(f"卡片图片 {tile_path} 不存在")
#
#     if not card_images:
#         raise Exception("没有找到任何卡片图片")
#
# except Exception as e:
#     print(f"卡片图片加载失败: {e}")
#     COLORS = [
#         (255, 0, 0),  # 红
#         (0, 255, 0),  # 绿
#         (0, 0, 255),  # 蓝
#         (255, 255, 0),  # 黄
#         (128, 0, 128),  # 紫
#     ]
#
# # 游戏状态
# slots = []
# score = 0
# game_over = False
# game_won = False
#
# def check_victory():
#     """检查是否胜利"""
#     for row in grid:
#         for stack in row:
#             if len(stack) > 0:
#                 return False
#     return len(slots) == 0
#
# # 初始化卡片堆
# grid = []
# for row in range(GRID_ROWS):
#     grid_row = []
#     for col in range(GRID_COLS):
#         layers = random.randint(3, 5)
#         max_card_type = len(card_images) - 1 if card_images else len(COLORS) - 1
#         stack = [random.randint(0, max_card_type) for _ in range(layers)]
#         stack += [stack[-1]] * (3 - layers % 3) if layers % 3 != 0 else []
#         grid_row.append(stack)
#     grid.append(grid_row)
#
# # 主循环
# clock = pygame.time.Clock()
# running = True
#
# while running:
#     # 事件处理
#     for event in pygame.event.get():
#         if event.type == pygame.QUIT:
#             running = False
#         elif event.type == pygame.MOUSEBUTTONDOWN and not game_over:
#             x, y = pygame.mouse.get_pos()
#             # 计算点击位置
#             grid_col = (x - GRID_LEFT) // (CARD_WIDTH + SPACING)
#             grid_row = (y - GRID_TOP) // (CARD_HEIGHT + SPACING)
#             # 检查点击范围
#             if 0 <= grid_row < GRID_ROWS and 0 <= grid_col < GRID_COLS:
#                 if len(grid[grid_row][grid_col]) > 0:
#                     # 检查槽位是否已满（改为7块）
#                     if len(slots) >= SLOT_COLS:  # SLOT_COLS = 7
#                         game_over = True
#                         continue
#
#                     # 取出顶层卡片
#                     card = grid[grid_row][grid_col].pop()
#                     slots.append(card)
#
#                     # 检查连续三个相同卡片
#                     if len(slots) >= 3 and slots[-1] == slots[-2] == slots[-3]:
#                         del slots[-3:]
#                         score += 1
#
#                     # 再次检查槽位是否已满
#                     if len(slots) >= SLOT_COLS:
#                         game_over = True
#
#                     # 检查胜利条件
#                     if check_victory():
#                         game_won = True
#                         game_over = True
#
#     # 移动背景图
#     bg_x -= BG_MOVE_SPEED
#     if bg_x <= -SCREEN_WIDTH:
#         bg_x = 0
#
#     # 绘制界面
#     if background_img:
#         screen.blit(background_img, (bg_x, 0))
#         screen.blit(background_img, (bg_x + SCREEN_WIDTH, 0))  # 绘制第二张背景图，实现无缝衔接
#     else:
#         screen.fill(BG_COLOR)
#
#     # 绘制卡片堆，添加叠罗汉效果
#     for row in range(GRID_ROWS):
#         for col in range(GRID_COLS):
#             x = GRID_LEFT + col * (CARD_WIDTH + SPACING)
#             y = GRID_TOP + row * (CARD_HEIGHT + SPACING)
#             stack = grid[row][col]
#             for i, card_type in enumerate(stack):
#                 offset_y = i * OVERLAP_OFFSET
#                 if card_images:
#                     screen.blit(card_images[card_type], (x, y + offset_y))
#                 else:
#                     pygame.draw.rect(screen, COLORS[card_type], (x, y + offset_y, CARD_WIDTH, CARD_HEIGHT))
#
#     # 绘制槽位背景
#     if slot_bg_img:
#         screen.blit(slot_bg_img, (SLOT_LEFT - 10, SLOT_TOP - 10))
#     else:
#         pygame.draw.rect(screen, (200, 200, 200),
#                          (SLOT_LEFT - 5, SLOT_TOP - 5,
#                           slot_width + 10, SLOT_HEIGHT + 10),
#                          border_radius=10)
#
#     # 绘制槽位中的卡片
#     for i, card in enumerate(slots):
#         x = SLOT_LEFT + i * (CARD_WIDTH + 5)
#         if card_images:
#             screen.blit(card_images[card], (x, SLOT_TOP))
#         else:
#             pygame.draw.rect(screen, COLORS[card], (x, SLOT_TOP, CARD_WIDTH, CARD_HEIGHT))
#
#     # 绘制状态信息
#     font = pygame.font.Font(None, 36)
#     text = font.render(f"Score: {score}", True, (0, 0, 0))
#     screen.blit(text, (20, 20))
#
#     # 绘制槽位容量提示
#     capacity_text = font.render(f"{len(slots)}/{SLOT_COLS}", True, (100, 100, 100))
#     screen.blit(capacity_text, (SCREEN_WIDTH - 60, 20))
#
#     if game_over:
#         text = font.render("YOU WIN!" if game_won else "GAME OVER!",
#                            True, (0, 255, 0) if game_won else (255, 0, 0))
#         screen.blit(text, (SCREEN_WIDTH // 2 - 80, SCREEN_HEIGHT // 2 - 20))
#
#     pygame.display.flip()
#     clock.tick(30)
#
# pygame.quit()

# import pygame
# import random
# import os
#
# # 初始化Pygame
# pygame.init()
#
# # 游戏窗口设置
# SCREEN_WIDTH = 480
# SCREEN_HEIGHT = 720
# screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
# pygame.display.set_caption("羊了个羊")
#
# # 颜色定义
# BG_COLOR = (255, 255, 255)
#
# # 卡片尺寸和间距
# CARD_WIDTH = 60
# CARD_HEIGHT = 80
# SPACING = 30
# # 叠罗汉偏移量
# OVERLAP_OFFSET = 5
#
# # 游戏区域布局
# GRID_ROWS = 4
# GRID_COLS = 4
# grid_width = GRID_COLS * (CARD_WIDTH + SPACING) - SPACING
# GRID_LEFT = (SCREEN_WIDTH - grid_width) // 2
# GRID_TOP = 100
#
# # 槽位区域设置
# SLOT_ROWS = 1
# SLOT_COLS = 7  # 最多存放7个卡片
# slot_width = SLOT_COLS * (CARD_WIDTH + 5) - 5
# SLOT_LEFT = (SCREEN_WIDTH - slot_width) // 2
# SLOT_TOP = SCREEN_HEIGHT - CARD_HEIGHT - 50
# SLOT_HEIGHT = CARD_HEIGHT + 20
#
# # 加载背景图像
# try:
#     image_folder = os.path.join(os.path.dirname(__file__), "image")
#     background_path = os.path.join(image_folder, "back.png")
#     background_img = pygame.image.load(background_path)
#     background_img = pygame.transform.scale(background_img, (SCREEN_WIDTH * 2, SCREEN_HEIGHT))  # 背景图宽度翻倍，用于移动
#     print("主背景图像加载成功")
#     bg_x = 0  # 背景图初始x坐标
#     BG_MOVE_SPEED = 1  # 背景图移动速度
# except Exception as e:
#     print(f"主背景图像加载失败: {e}")
#     background_img = None
#     bg_x = 0
#
# # 加载槽位背景图像
# try:
#     slot_bg_path = os.path.join(image_folder, "back2.png")
#     slot_bg_img = pygame.image.load(slot_bg_path)
#     slot_bg_img = pygame.transform.scale(slot_bg_img, (slot_width + 20, SLOT_HEIGHT + 20))
#     print("槽位背景图像加载成功")
# except Exception as e:
#     print(f"槽位背景图像加载失败: {e}")
#     slot_bg_img = None
#
# # 加载卡片图片
# card_images = []
# try:
#     for i in range(5):
#         if i == 0:
#             tile_path = os.path.join(image_folder, "tile.png")
#         else:
#             tile_path = os.path.join(image_folder, f"tile{i}.png")
#
#         if os.path.exists(tile_path):
#             img = pygame.image.load(tile_path)
#             img = pygame.transform.scale(img, (CARD_WIDTH, CARD_HEIGHT))
#             card_images.append(img)
#             print(f"卡片图片 {os.path.basename(tile_path)} 加载成功")
#         else:
#             print(f"卡片图片 {tile_path} 不存在")
#
#     if not card_images:
#         raise Exception("没有找到任何卡片图片")
#
# except Exception as e:
#     print(f"卡片图片加载失败: {e}")
#     COLORS = [
#         (255, 0, 0),  # 红
#         (0, 255, 0),  # 绿
#         (0, 0, 255),  # 蓝
#         (255, 255, 0),  # 黄
#         (128, 0, 128),  # 紫
#     ]
#
# # 游戏状态
# slots = []
# score = 0
# game_over = False
# game_won = False
# # 消去动画相关变量
# eliminate_animation = False
# eliminate_index = None
# animation_timer = 0
# ANIMATION_DURATION = 10
#
#
# def check_victory():
#     """检查是否胜利"""
#     for row in grid:
#         for stack in row:
#             if len(stack) > 0:
#                 return False
#     return len(slots) == 0
#
#
# # 初始化卡片堆
# grid = []
# for row in range(GRID_ROWS):
#     grid_row = []
#     for col in range(GRID_COLS):
#         layers = random.randint(3, 5)
#         max_card_type = len(card_images) - 1 if card_images else len(COLORS) - 1
#         stack = [random.randint(0, max_card_type) for _ in range(layers)]
#         stack += [stack[-1]] * (3 - layers % 3) if layers % 3 != 0 else []
#         grid_row.append(stack)
#     grid.append(grid_row)
#
# # 主循环
# clock = pygame.time.Clock()
# running = True
#
# while running:
#     # 事件处理
#     for event in pygame.event.get():
#         if event.type == pygame.QUIT:
#             running = False
#         elif event.type == pygame.MOUSEBUTTONDOWN and not game_over:
#             x, y = pygame.mouse.get_pos()
#             # 计算点击位置
#             grid_col = (x - GRID_LEFT) // (CARD_WIDTH + SPACING)
#             grid_row = (y - GRID_TOP) // (CARD_HEIGHT + SPACING)
#             # 检查点击范围
#             if 0 <= grid_row < GRID_ROWS and 0 <= grid_col < GRID_COLS:
#                 if len(grid[grid_row][grid_col]) > 0:
#                     # 检查槽位是否已满（改为7块）
#                     if len(slots) >= SLOT_COLS:  # SLOT_COLS = 7
#                         game_over = True
#                         continue
#
#                     # 取出顶层卡片
#                     card = grid[grid_row][grid_col].pop()
#                     slots.append(card)
#
#                     # 检查连续三个相同卡片
#                     if len(slots) >= 3 and slots[-1] == slots[-2] == slots[-3]:
#                         eliminate_animation = True
#                         eliminate_index = len(slots) - 3
#                         score += 1
#
#                     # 再次检查槽位是否已满
#                     if len(slots) >= SLOT_COLS:
#                         game_over = True
#
#                     # 检查胜利条件
#                     if check_victory():
#                         game_won = True
#                         game_over = True
#
#     # 移动背景图
#     bg_x -= BG_MOVE_SPEED
#     if bg_x <= -SCREEN_WIDTH:
#         bg_x = 0
#
#     # 绘制界面
#     if background_img:
#         screen.blit(background_img, (bg_x, 0))
#         screen.blit(background_img, (bg_x + SCREEN_WIDTH, 0))  # 绘制第二张背景图，实现无缝衔接
#     else:
#         screen.fill(BG_COLOR)
#
#     # 绘制卡片堆，添加叠罗汉效果
#     for row in range(GRID_ROWS):
#         for col in range(GRID_COLS):
#             x = GRID_LEFT + col * (CARD_WIDTH + SPACING)
#             y = GRID_TOP + row * (CARD_HEIGHT + SPACING)
#             stack = grid[row][col]
#             for i, card_type in enumerate(stack):
#                 offset_y = i * OVERLAP_OFFSET
#                 if card_images:
#                     screen.blit(card_images[card_type], (x, y + offset_y))
#                 else:
#                     pygame.draw.rect(screen, COLORS[card_type], (x, y + offset_y, CARD_WIDTH, CARD_HEIGHT))
#
#     # 绘制槽位背景
#     if slot_bg_img:
#         screen.blit(slot_bg_img, (SLOT_LEFT - 10, SLOT_TOP - 10))
#     else:
#         pygame.draw.rect(screen, (200, 200, 200),
#                          (SLOT_LEFT - 5, SLOT_TOP - 5,
#                           slot_width + 10, SLOT_HEIGHT + 10),
#                          border_radius=10)
#
#     # 绘制槽位中的卡片
#     for i, card in enumerate(slots):
#         if eliminate_animation and i >= eliminate_index and i < eliminate_index + 3:
#             alpha = 255 - (animation_timer * (255 // ANIMATION_DURATION))
#             if card_images:
#                 img = card_images[card].copy()
#                 img.set_alpha(alpha)
#                 screen.blit(img, (SLOT_LEFT + i * (CARD_WIDTH + 5), SLOT_TOP))
#             else:
#                 surface = pygame.Surface((CARD_WIDTH, CARD_HEIGHT))
#                 surface.set_alpha(alpha)
#                 surface.fill(COLORS[card])
#                 screen.blit(surface, (SLOT_LEFT + i * (CARD_WIDTH + 5), SLOT_TOP))
#         else:
#             x = SLOT_LEFT + i * (CARD_WIDTH + 5)
#             if card_images:
#                 screen.blit(card_images[card], (x, SLOT_TOP))
#             else:
#                 pygame.draw.rect(screen, COLORS[card], (x, SLOT_TOP, CARD_WIDTH, CARD_HEIGHT))
#
#     # 处理消去动画
#     if eliminate_animation:
#         animation_timer += 1
#         if animation_timer >= ANIMATION_DURATION:
#             del slots[eliminate_index:eliminate_index + 3]
#             eliminate_animation = False
#             animation_timer = 0
#             eliminate_index = None
#
#     # 绘制状态信息
#     font = pygame.font.Font(None, 36)
#     text = font.render(f"Score: {score}", True, (0, 0, 0))
#     screen.blit(text, (20, 20))
#
#     # 绘制槽位容量提示
#     capacity_text = font.render(f"{len(slots)}/{SLOT_COLS}", True, (100, 100, 100))
#     screen.blit(capacity_text, (SCREEN_WIDTH - 60, 20))
#
#     if game_over:
#         text = font.render("YOU WIN!" if game_won else "GAME OVER!",
#                            True, (0, 255, 0) if game_won else (255, 0, 0))
#         screen.blit(text, (SCREEN_WIDTH // 2 - 80, SCREEN_HEIGHT // 2 - 20))
#
#     pygame.display.flip()
#     clock.tick(30)
#
# pygame.quit()


# import pygame
# import random
# import os
#
# # 初始化Pygame
# pygame.init()
#
# # 游戏窗口设置
# SCREEN_WIDTH = 480
# SCREEN_HEIGHT = 720
# screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
# pygame.display.set_caption("羊了个羊")
#
# # 颜色定义
# BG_COLOR = (255, 255, 255)
#
# # 卡片尺寸和间距
# CARD_WIDTH = 60
# CARD_HEIGHT = 80
# SPACING = 30
# # 叠罗汉偏移量
# OVERLAP_OFFSET = 5
#
# # 游戏区域布局
# GRID_ROWS = 4
# GRID_COLS = 4
# grid_width = GRID_COLS * (CARD_WIDTH + SPACING) - SPACING
# GRID_LEFT = (SCREEN_WIDTH - grid_width) // 2
# GRID_TOP = 100
#
# # 槽位区域设置
# SLOT_ROWS = 1
# SLOT_COLS = 7  # 最多存放7个卡片
# slot_width = SLOT_COLS * (CARD_WIDTH + 5) - 5
# SLOT_LEFT = (SCREEN_WIDTH - slot_width) // 2
# SLOT_TOP = SCREEN_HEIGHT - CARD_HEIGHT - 50
# SLOT_HEIGHT = CARD_HEIGHT + 20
#
# # 道具按钮设置
# ITEM_WIDTH = 80
# ITEM_HEIGHT = 40
# ITEM_SPACING = 20
# ITEM_LEFT = (SCREEN_WIDTH - (2 * ITEM_WIDTH + ITEM_SPACING)) // 2
# ITEM_TOP = 20
#
# # 加载背景图像
# try:
#     image_folder = os.path.join(os.path.dirname(__file__), "image")
#     background_path = os.path.join(image_folder, "back.png")
#     background_img = pygame.image.load(background_path)
#     background_img = pygame.transform.scale(background_img, (SCREEN_WIDTH * 2, SCREEN_HEIGHT))  # 背景图宽度翻倍，用于移动
#     print("主背景图像加载成功")
#     bg_x = 0  # 背景图初始x坐标
#     BG_MOVE_SPEED = 1  # 背景图移动速度
# except Exception as e:
#     print(f"主背景图像加载失败: {e}")
#     background_img = None
#     bg_x = 0
#
# # 加载槽位背景图像
# try:
#     slot_bg_path = os.path.join(image_folder, "back2.png")
#     slot_bg_img = pygame.image.load(slot_bg_path)
#     slot_bg_img = pygame.transform.scale(slot_bg_img, (slot_width + 20, SLOT_HEIGHT + 20))
#     print("槽位背景图像加载成功")
# except Exception as e:
#     print(f"槽位背景图像加载失败: {e}")
#     slot_bg_img = None
#
# # 加载卡片图片
# card_images = []
# try:
#     for i in range(5):
#         if i == 0:
#             tile_path = os.path.join(image_folder, "tile.png")
#         else:
#             tile_path = os.path.join(image_folder, f"tile{i}.png")
#
#         if os.path.exists(tile_path):
#             img = pygame.image.load(tile_path)
#             img = pygame.transform.scale(img, (CARD_WIDTH, CARD_HEIGHT))
#             card_images.append(img)
#             print(f"卡片图片 {os.path.basename(tile_path)} 加载成功")
#         else:
#             print(f"卡片图片 {tile_path} 不存在")
#
#     if not card_images:
#         raise Exception("没有找到任何卡片图片")
#
# except Exception as e:
#     print(f"卡片图片加载失败: {e}")
#     COLORS = [
#         (255, 0, 0),  # 红
#         (0, 255, 0),  # 绿
#         (0, 0, 255),  # 蓝
#         (255, 255, 0),  # 黄
#         (128, 0, 128),  # 紫
#     ]
#
# # 游戏状态
# slots = []
# score = 0
# game_over = False
# game_won = False
# # 消去动画相关变量
# eliminate_animation = False
# eliminate_index = None
# animation_timer = 0
# ANIMATION_DURATION = 10
#
# # 道具数量
# remove_card_count = 3
# shuffle_count = 3
#
#
# def check_victory():
#     """检查是否胜利"""
#     for row in grid:
#         for stack in row:
#             if len(stack) > 0:
#                 return False
#     return len(slots) == 0
#
#
# def remove_card():
#     global remove_card_count
#     if remove_card_count > 0 and slots:
#         slots.pop()
#         remove_card_count -= 1
#
#
# def shuffle_grid():
#     global shuffle_count
#     if shuffle_count > 0:
#         all_cards = []
#         for row in grid:
#             for stack in row:
#                 all_cards.extend(stack)
#                 stack.clear()
#         random.shuffle(all_cards)
#         index = 0
#         for row in grid:
#             for stack in row:
#                 layers = random.randint(3, 5)
#                 stack.extend(all_cards[index:index + layers])
#                 index += layers
#         shuffle_count -= 1
#
#
# # 初始化卡片堆
# grid = []
# for row in range(GRID_ROWS):
#     grid_row = []
#     for col in range(GRID_COLS):
#         layers = random.randint(3, 5)
#         max_card_type = len(card_images) - 1 if card_images else len(COLORS) - 1
#         stack = [random.randint(0, max_card_type) for _ in range(layers)]
#         stack += [stack[-1]] * (3 - layers % 3) if layers % 3 != 0 else []
#         grid_row.append(stack)
#     grid.append(grid_row)
#
# # 主循环
# clock = pygame.time.Clock()
# running = True
#
# while running:
#     # 事件处理
#     for event in pygame.event.get():
#         if event.type == pygame.QUIT:
#             running = False
#         elif event.type == pygame.MOUSEBUTTONDOWN and not game_over:
#             x, y = pygame.mouse.get_pos()
#             # 检查是否点击道具按钮
#             if ITEM_LEFT <= x <= ITEM_LEFT + ITEM_WIDTH and ITEM_TOP <= y <= ITEM_TOP + ITEM_HEIGHT:
#                 remove_card()
#             elif ITEM_LEFT + ITEM_WIDTH + ITEM_SPACING <= x <= ITEM_LEFT + 2 * ITEM_WIDTH + ITEM_SPACING and ITEM_TOP <= y <= ITEM_TOP + ITEM_HEIGHT:
#                 shuffle_grid()
#             else:
#                 # 计算点击位置
#                 grid_col = (x - GRID_LEFT) // (CARD_WIDTH + SPACING)
#                 grid_row = (y - GRID_TOP) // (CARD_HEIGHT + SPACING)
#                 # 检查点击范围
#                 if 0 <= grid_row < GRID_ROWS and 0 <= grid_col < GRID_COLS:
#                     if len(grid[grid_row][grid_col]) > 0:
#                         # 检查槽位是否已满（改为7块）
#                         if len(slots) >= SLOT_COLS:  # SLOT_COLS = 7
#                             game_over = True
#                             continue
#
#                         # 取出顶层卡片
#                         card = grid[grid_row][grid_col].pop()
#                         slots.append(card)
#
#                         # 检查连续三个相同卡片
#                         if len(slots) >= 3 and slots[-1] == slots[-2] == slots[-3]:
#                             eliminate_animation = True
#                             eliminate_index = len(slots) - 3
#                             score += 1
#
#                         # 再次检查槽位是否已满
#                         if len(slots) >= SLOT_COLS:
#                             game_over = True
#
#                         # 检查胜利条件
#                         if check_victory():
#                             game_won = True
#                             game_over = True
#
#     # 移动背景图
#     bg_x -= BG_MOVE_SPEED
#     if bg_x <= -SCREEN_WIDTH:
#         bg_x = 0
#
#     # 绘制界面
#     if background_img:
#         screen.blit(background_img, (bg_x, 0))
#         screen.blit(background_img, (bg_x + SCREEN_WIDTH, 0))  # 绘制第二张背景图，实现无缝衔接
#     else:
#         screen.fill(BG_COLOR)
#
#     # 绘制卡片堆，添加叠罗汉效果
#     for row in range(GRID_ROWS):
#         for col in range(GRID_COLS):
#             x = GRID_LEFT + col * (CARD_WIDTH + SPACING)
#             y = GRID_TOP + row * (CARD_HEIGHT + SPACING)
#             stack = grid[row][col]
#             for i, card_type in enumerate(stack):
#                 offset_y = i * OVERLAP_OFFSET
#                 if card_images:
#                     screen.blit(card_images[card_type], (x, y + offset_y))
#                 else:
#                     pygame.draw.rect(screen, COLORS[card_type], (x, y + offset_y, CARD_WIDTH, CARD_HEIGHT))
#
#     # 绘制槽位背景
#     if slot_bg_img:
#         screen.blit(slot_bg_img, (SLOT_LEFT - 10, SLOT_TOP - 10))
#     else:
#         pygame.draw.rect(screen, (200, 200, 200),
#                          (SLOT_LEFT - 5, SLOT_TOP - 5,
#                           slot_width + 10, SLOT_HEIGHT + 10),
#                          border_radius=10)
#
#     # 绘制槽位中的卡片
#     for i, card in enumerate(slots):
#         if eliminate_animation and i >= eliminate_index and i < eliminate_index + 3:
#             alpha = 255 - (animation_timer * (255 // ANIMATION_DURATION))
#             if card_images:
#                 img = card_images[card].copy()
#                 img.set_alpha(alpha)
#                 screen.blit(img, (SLOT_LEFT + i * (CARD_WIDTH + 5), SLOT_TOP))
#             else:
#                 surface = pygame.Surface((CARD_WIDTH, CARD_HEIGHT))
#                 surface.set_alpha(alpha)
#                 surface.fill(COLORS[card])
#                 screen.blit(surface, (SLOT_LEFT + i * (CARD_WIDTH + 5), SLOT_TOP))
#         else:
#             x = SLOT_LEFT + i * (CARD_WIDTH + 5)
#             if card_images:
#                 screen.blit(card_images[card], (x, SLOT_TOP))
#             else:
#                 pygame.draw.rect(screen, COLORS[card], (x, SLOT_TOP, CARD_WIDTH, CARD_HEIGHT))
#
#     # 处理消去动画
#     if eliminate_animation:
#         animation_timer += 1
#         if animation_timer >= ANIMATION_DURATION:
#             del slots[eliminate_index:eliminate_index + 3]
#             eliminate_animation = False
#             animation_timer = 0
#             eliminate_index = None
#
#     # 绘制状态信息
#     font = pygame.font.Font(None, 36)
#     text = font.render(f"Score: {score}", True, (0, 0, 0))
#     screen.blit(text, (20, 20))
#
#     # 绘制槽位容量提示
#     capacity_text = font.render(f"{len(slots)}/{SLOT_COLS}", True, (100, 100, 100))
#     screen.blit(capacity_text, (SCREEN_WIDTH - 60, 20))
#
#     # 绘制道具按钮
#     pygame.draw.rect(screen, (0, 128, 0), (ITEM_LEFT, ITEM_TOP, ITEM_WIDTH, ITEM_HEIGHT))
#     pygame.draw.rect(screen, (0, 0, 128), (ITEM_LEFT + ITEM_WIDTH + ITEM_SPACING, ITEM_TOP, ITEM_WIDTH, ITEM_HEIGHT))
#     font = pygame.font.Font(None, 24)
#     remove_text = font.render(f"移除: {remove_card_count}", True, (255, 255, 255))
#     shuffle_text = font.render(f"洗牌: {shuffle_count}", True, (255, 255, 255))
#     screen.blit(remove_text, (ITEM_LEFT + 10, ITEM_TOP + 10))
#     screen.blit(shuffle_text, (ITEM_LEFT + ITEM_WIDTH + ITEM_SPACING + 10, ITEM_TOP + 10))
#
#     if game_over:
#         text = font.render("YOU WIN!" if game_won else "GAME OVER!",
#                            True, (0, 255, 0) if game_won else (255, 0, 0))
#         screen.blit(text, (SCREEN_WIDTH // 2 - 80, SCREEN_HEIGHT // 2 - 20))
#
#     pygame.display.flip()
#     clock.tick(30)
#
# pygame.quit()







import pygame
import random
import os

# 初始化Pygame
pygame.init()

# 游戏窗口设置
SCREEN_WIDTH = 480
SCREEN_HEIGHT = 720
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("羊了个羊")

# 颜色定义
BG_COLOR = (255, 255, 255)

# 卡片尺寸和间距
CARD_WIDTH = 60
CARD_HEIGHT = 80
SPACING = 30
# 叠罗汉偏移量
OVERLAP_OFFSET = 5

# 游戏区域布局
GRID_ROWS = 4
GRID_COLS = 4
grid_width = GRID_COLS * (CARD_WIDTH + SPACING) - SPACING
GRID_LEFT = (SCREEN_WIDTH - grid_width) // 2
GRID_TOP = 100

# 槽位区域设置
SLOT_ROWS = 1
SLOT_COLS = 7  # 最多存放7个卡片
slot_width = SLOT_COLS * (CARD_WIDTH + 5) - 5
SLOT_LEFT = (SCREEN_WIDTH - slot_width) // 2
SLOT_TOP = SCREEN_HEIGHT - CARD_HEIGHT - 50
SLOT_HEIGHT = CARD_HEIGHT + 20

# 道具按钮设置
ITEM_WIDTH = 80
ITEM_HEIGHT = 40
ITEM_SPACING = 20
ITEM_LEFT = (SCREEN_WIDTH - (2 * ITEM_WIDTH + ITEM_SPACING)) // 2
ITEM_TOP = 20

# 加载背景图像
try:
    image_folder = os.path.join(os.path.dirname(__file__), "image")
    background_path = os.path.join(image_folder, "back.png")
    background_img = pygame.image.load(background_path)
    background_img = pygame.transform.scale(background_img, (SCREEN_WIDTH * 2, SCREEN_HEIGHT))  # 背景图宽度翻倍，用于移动
    print("主背景图像加载成功")
    bg_x = 0  # 背景图初始x坐标
    BG_MOVE_SPEED = 1  # 背景图移动速度
except Exception as e:
    print(f"主背景图像加载失败: {e}")
    background_img = None
    bg_x = 0

# 加载槽位背景图像
try:
    slot_bg_path = os.path.join(image_folder, "back2.png")
    slot_bg_img = pygame.image.load(slot_bg_path)
    slot_bg_img = pygame.transform.scale(slot_bg_img, (slot_width + 20, SLOT_HEIGHT + 20))
    print("槽位背景图像加载成功")
except Exception as e:
    print(f"槽位背景图像加载失败: {e}")
    slot_bg_img = None

# 加载卡片图片
card_images = []
try:
    for i in range(5):
        if i == 0:
            tile_path = os.path.join(image_folder, "tile.png")
        else:
            tile_path = os.path.join(image_folder, f"tile{i}.png")

        if os.path.exists(tile_path):
            img = pygame.image.load(tile_path)
            img = pygame.transform.scale(img, (CARD_WIDTH, CARD_HEIGHT))
            card_images.append(img)
            print(f"卡片图片 {os.path.basename(tile_path)} 加载成功")
        else:
            print(f"卡片图片 {tile_path} 不存在")

    if not card_images:
        raise Exception("没有找到任何卡片图片")

except Exception as e:
    print(f"卡片图片加载失败: {e}")
    COLORS = [
        (255, 0, 0),  # 红
        (0, 255, 0),  # 绿
        (0, 0, 255),  # 蓝
        (255, 255, 0),  # 黄
        (128, 0, 128),  # 紫
    ]

# 游戏状态
slots = []
score = 0
game_over = False
game_won = False
# 消去动画相关变量
eliminate_animation = False
eliminate_index = None
animation_timer = 0
ANIMATION_DURATION = 10

# 道具数量
remove_card_count = 3
shuffle_count = 3

# 卡片移动动画相关变量
card_moving = False
moving_card = None
start_x = 0
start_y = 0
target_x = 0
target_y = 0
move_timer = 0
MOVE_DURATION = 20


def check_victory():
    """检查是否胜利"""
    for row in grid:
        for stack in row:
            if len(stack) > 0:
                return False
    return len(slots) == 0


def remove_card():
    global remove_card_count
    if remove_card_count > 0 and slots:
        slots.pop()
        remove_card_count -= 1


def shuffle_grid():
    global shuffle_count
    if shuffle_count > 0:
        all_cards = []
        for row in grid:
            for stack in row:
                all_cards.extend(stack)
                stack.clear()
        random.shuffle(all_cards)
        index = 0
        for row in grid:
            for stack in row:
                layers = random.randint(3, 5)
                stack.extend(all_cards[index:index + layers])
                index += layers
        shuffle_count -= 1


# 初始化卡片堆
grid = []
for row in range(GRID_ROWS):
    grid_row = []
    for col in range(GRID_COLS):
        layers = random.randint(3, 5)
        max_card_type = len(card_images) - 1 if card_images else len(COLORS) - 1
        stack = [random.randint(0, max_card_type) for _ in range(layers)]
        stack += [stack[-1]] * (3 - layers % 3) if layers % 3 != 0 else []
        grid_row.append(stack)
    grid.append(grid_row)

# 主循环
clock = pygame.time.Clock()
running = True

while running:
    # 事件处理
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.MOUSEBUTTONDOWN and not game_over:
            x, y = pygame.mouse.get_pos()
            # 检查是否点击道具按钮
            if ITEM_LEFT <= x <= ITEM_LEFT + ITEM_WIDTH and ITEM_TOP <= y <= ITEM_TOP + ITEM_HEIGHT:
                remove_card()
            elif ITEM_LEFT + ITEM_WIDTH + ITEM_SPACING <= x <= ITEM_LEFT + 2 * ITEM_WIDTH + ITEM_SPACING and ITEM_TOP <= y <= ITEM_TOP + ITEM_HEIGHT:
                shuffle_grid()
            else:
                # 计算点击位置
                grid_col = (x - GRID_LEFT) // (CARD_WIDTH + SPACING)
                grid_row = (y - GRID_TOP) // (CARD_HEIGHT + SPACING)
                # 检查点击范围
                if 0 <= grid_row < GRID_ROWS and 0 <= grid_col < GRID_COLS:
                    if len(grid[grid_row][grid_col]) > 0:
                        # 检查槽位是否已满（改为7块）
                        if len(slots) >= SLOT_COLS:
                            game_over = True
                            continue

                        # 取出顶层卡片
                        moving_card = grid[grid_row][grid_col].pop()
                        start_x = GRID_LEFT + grid_col * (CARD_WIDTH + SPACING)
                        start_y = GRID_TOP + grid_row * (CARD_HEIGHT + SPACING) + (len(grid[grid_row][grid_col])) * OVERLAP_OFFSET
                        target_x = SLOT_LEFT + len(slots) * (CARD_WIDTH + 5)
                        target_y = SLOT_TOP
                        card_moving = True
                        move_timer = 0

    # 移动背景图
    bg_x -= BG_MOVE_SPEED
    if bg_x <= -SCREEN_WIDTH:
        bg_x = 0

    # 绘制界面
    if background_img:
        screen.blit(background_img, (bg_x, 0))
        screen.blit(background_img, (bg_x + SCREEN_WIDTH, 0))  # 绘制第二张背景图，实现无缝衔接
    else:
        screen.fill(BG_COLOR)

    # 绘制卡片堆，添加叠罗汉效果
    for row in range(GRID_ROWS):
        for col in range(GRID_COLS):
            x = GRID_LEFT + col * (CARD_WIDTH + SPACING)
            y = GRID_TOP + row * (CARD_HEIGHT + SPACING)
            stack = grid[row][col]
            for i, card_type in enumerate(stack):
                offset_y = i * OVERLAP_OFFSET
                if card_images:
                    screen.blit(card_images[card_type], (x, y + offset_y))
                else:
                    pygame.draw.rect(screen, COLORS[card_type], (x, y + offset_y, CARD_WIDTH, CARD_HEIGHT))

    # 绘制槽位背景
    if slot_bg_img:
        screen.blit(slot_bg_img, (SLOT_LEFT - 10, SLOT_TOP - 10))
    else:
        pygame.draw.rect(screen, (200, 200, 200),
                         (SLOT_LEFT - 5, SLOT_TOP - 5,
                          slot_width + 10, SLOT_HEIGHT + 10),
                         border_radius=10)

    # 绘制槽位中的卡片
    for i, card in enumerate(slots):
        if eliminate_animation and i >= eliminate_index and i < eliminate_index + 3:
            alpha = 255 - (animation_timer * (255 // ANIMATION_DURATION))
            if card_images:
                img = card_images[card].copy()
                img.set_alpha(alpha)
                screen.blit(img, (SLOT_LEFT + i * (CARD_WIDTH + 5), SLOT_TOP))
            else:
                surface = pygame.Surface((CARD_WIDTH, CARD_HEIGHT))
                surface.set_alpha(alpha)
                surface.fill(COLORS[card])
                screen.blit(surface, (SLOT_LEFT + i * (CARD_WIDTH + 5), SLOT_TOP))
        else:
            x = SLOT_LEFT + i * (CARD_WIDTH + 5)
            if card_images:
                screen.blit(card_images[card], (x, SLOT_TOP))
            else:
                pygame.draw.rect(screen, COLORS[card], (x, SLOT_TOP, CARD_WIDTH, CARD_HEIGHT))

    # 处理卡片移动动画
    if card_moving:
        progress = move_timer / MOVE_DURATION
        current_x = start_x + (target_x - start_x) * progress
        current_y = start_y + (target_y - start_y) * progress
        if card_images:
            screen.blit(card_images[moving_card], (current_x, current_y))
        else:
            pygame.draw.rect(screen, COLORS[moving_card], (current_x, current_y, CARD_WIDTH, CARD_HEIGHT))
        move_timer += 1
        if move_timer >= MOVE_DURATION:
            slots.append(moving_card)
            card_moving = False
            moving_card = None
            # 检查连续三个相同卡片
            if len(slots) >= 3 and slots[-1] == slots[-2] == slots[-3]:
                eliminate_animation = True
                eliminate_index = len(slots) - 3
                score += 1

            # 再次检查槽位是否已满
            if len(slots) >= SLOT_COLS:
                game_over = True

            # 检查胜利条件
            if check_victory():
                game_won = True
                game_over = True

    # 处理消去动画
    if eliminate_animation:
        animation_timer += 1
        if animation_timer >= ANIMATION_DURATION:
            del slots[eliminate_index:eliminate_index + 3]
            eliminate_animation = False
            animation_timer = 0
            eliminate_index = None

    # 绘制状态信息
    font = pygame.font.Font(None, 36)
    text = font.render(f"Score: {score}", True, (0, 0, 0))
    screen.blit(text, (20, 20))

    # 绘制槽位容量提示
    capacity_text = font.render(f"{len(slots)}/{SLOT_COLS}", True, (100, 100, 100))
    screen.blit(capacity_text, (SCREEN_WIDTH - 60, 20))

    # 绘制道具按钮
    pygame.draw.rect(screen, (0, 128, 0), (ITEM_LEFT, ITEM_TOP, ITEM_WIDTH, ITEM_HEIGHT))
    pygame.draw.rect(screen, (0, 0, 128), (ITEM_LEFT + ITEM_WIDTH + ITEM_SPACING, ITEM_TOP, ITEM_WIDTH, ITEM_HEIGHT))
    font = pygame.font.Font(None, 24)
    remove_text = font.render(f"移除: {remove_card_count}", True, (255, 255, 255))
    shuffle_text = font.render(f"洗牌: {shuffle_count}", True, (255, 255, 255))
    screen.blit(remove_text, (ITEM_LEFT + 10, ITEM_TOP + 10))
    screen.blit(shuffle_text, (ITEM_LEFT + ITEM_WIDTH + ITEM_SPACING + 10, ITEM_TOP + 10))

    if game_over:
        text = font.render("YOU WIN!" if game_won else "GAME OVER!",
                           True, (0, 255, 0) if game_won else (255, 0, 0))
        screen.blit(text, (SCREEN_WIDTH // 2 - 80, SCREEN_HEIGHT // 2 - 20))

    pygame.display.flip()
    clock.tick(30)

pygame.quit()